package com.ludomancy.sos64.components;

import java.awt.Graphics;
import java.awt.Point;
import com.ludomancy.gamelib.ImageAnimation;
import com.ludomancy.gamelib.ImageStrip;
import com.ludomancy.gamelib.ResourceManager;
import com.ludomancy.gamelib.Sound;
import com.ludomancy.gamelib.Utils;
import com.ludomancy.sos64.Accumulator;
import com.ludomancy.sos64.Component;
import com.ludomancy.sos64.Game;

public class Platform extends Component
{
	private ImageAnimation platform;
	private ImageAnimation ray;
	private Accumulator rayAccum = new Accumulator(2200);
	private boolean rayFired = false;
	private Component grown64;
	private Generator generator;
	private boolean eggGenerated = false;
	
	public Platform(Generator builder)
	{
		super(0,0);
		generator = builder;
		if(platform == null)
		{
			platform = new ImageAnimation(new ImageStrip(ResourceManager.getImage("platform.png"), 38, 19), 4);
			ray = new ImageAnimation(new ImageStrip(ResourceManager.getImage("ray.png"), 45, 14), 1);
			ray.looping = true;
		}
		x = builder.x + builder.getSize().x;
		y = builder.y + builder.getSize().y - getSize().y;
	}
	
	public Point getSize()
	{
		return new Point(38,19);
	}
	
	public boolean isOrganic()
	{
		return true;
	}
	
	public void onCollided(Component other)
	{
		if(other instanceof Teen64 && generator.active)
		{
			// start crazy animation
			Sound.play("beat.wav");
			rayFired = true;
			ray.play();
			grown64 = other;
			Game.game.components.remove(grown64);
			Adult64 egg = new Adult64(getHotspot());
			egg.x -= egg.getSize().x/2;
			egg.y -= egg.getSize().y - 4;
			Game.game.add(egg);
		}
	}
	
	public boolean canMove()
	{
		return false;
	}

	public void paint(Graphics g, int px, int py)
	{
		platform.paintCurrentFrame(g, px, py);
		if(rayFired && !eggGenerated)
		{
			int offsetY = y + getSize().y - ray.strip.frameHeight - 5;
			int blocks = (y + getSize().y)/ray.strip.frameHeight;
			int offset = Math.abs((int)System.currentTimeMillis());
			for (int i = 0; i < blocks; i++)
			{
				ray.strip.paint(g, (i+offset) % ray.strip.getImageCount(), x+getSize().x/2, offsetY, Utils.ANCHOR_HCENTER);
				offsetY -= ray.strip.frameHeight;
			}
		}
	}
	
	public void update()
	{
		ray.update();
		platform.update();
		if(rayFired && !eggGenerated)
		{
			rayAccum.update();
			if(rayAccum.isDone())
			{
				eggGenerated = true;
			}
		}
	}
}
